<template>
	<div class="detail">
<!-- 		<div class="imageBox">
			<image :src="imageName('/bgImage.png')" style="width:100%; height:100%;" mode="scaleToFill"></image>
		</div> -->
		<div class="bottomImageBox">
			<div v-show="!isSuccse">
				<image v-if="!isError" :src="imageName('/bg-no-discharge-noshadow.png')" style="width: 100%;"
					mode="widthFix"></image>
				<image v-else :src="imageName('/bg-error-discharge-noshadow.png')" style="width: 100%;" mode="widthFix">
				</image>
			</div>
			<div v-show="isSuccse">
				<image class="succes-image-Box" :src="imageName('/bg-succes-discharge-noshadow.png')"
					style="width: 100%;" mode="widthFix">
				</image>
				<div class="title-succes-one">放电中</div>
				<div class="title-succes-two">{{car}}%</div>
				<div class="title-succes-three">车辆剩余电量</div>
			</div>
		</div>
		<div class="bottomImageBox">
			<image :src="imageName('/bottom-unsmooth-noshadow.png')" style="width: 100%;" mode="widthFix"></image>
		</div>
		<div class="topImageBox">
			<image :src="imageName('/bg-top-tilte-noshadow.png')" style="width: 100%;" mode="widthFix"></image>
		</div>

		<div class="bottomImageBox" v-if="!isSuccse">
			<image :src="imageName('/bg-no-discharge-noshadow-title.png')" style="width: 100%;" mode="widthFix"></image>
			<div v-if="!isError">
				<div class="title-one">感谢您使用唯电宝移动电站</div>
				<div class="title-two">启动前请仔细阅读说明书</div>
				<div class="title-three">可关注微信公众号</div>
				<div class="title-four">「唯电新能源汽车社区」</div>
				<div class="title-five">查看视频指示说明</div>
			</div>
			<div v-else>
				<div class="title-one">放电产生异常</div>
				<div class="title-two">不代表设备故障</div>
				<div class="title-three">请根据说明书检查使用环境</div>
				<div class="title-four">或联系官方客服咨询</div>
				<div class="title-five">微信号weidiankjz001</div>
			</div>
		</div>
		<div class="bottomImageBox" v-if="!isSuccse">
			<div>
				<div v-if="!isError">
					<image :src="imageName('/bg-no-discharge-center.png')" style="width: 100%;" mode="widthFix"></image>
					<div class="title-not-started">设备未启动</div>
				</div>
				<div v-else>
					<image :src="imageName('/bg-error-discharge-center.png')" style="width: 100%;" mode="widthFix">
					</image>
					<div class="title-error-started">{{errorName}}</div>
				</div>
			</div>
		</div>
		<div class="bottomImageBox" v-if="isSuccse">
			<image :src="imageName('/bg-line-image.png')" style="width: 100%;" mode="widthFix" v-if="!isSingleChannel"></image>
			<div :class="(isSingleChannel)?'title-line-singleOne':'title-line-one'">{{thoroughfareOne}}kW</div>
			<div class="title-line-two" v-if="!isSingleChannel">10A插座实时功率</div>
			<div class="title-line-singleTwo" v-else>插座实时功率</div>
			<div class="title-line-three" v-if="!isSingleChannel">{{thoroughfareTwo}}kW</div>
			<div class="title-line-four" v-if="!isSingleChannel">16A插座实时功率</div>
		</div>

		<div class="bottomImageBox">
			<image :src="(isSuccse)?imageName('/bg-bottom-succes-button.png'):imageName('/bg-bottom-button.png')"
				style="width: 100%;" mode="widthFix"></image>
			<div :class="(isSuccse)?'titlebox':'title-not-Box'" @click="closeCar()">紧急停机</div>
		</div>

		<div class="upgradeBox" v-if="isUpdata">
			<image src="@/static/upgradeBox.png" style="width:100%;" mode="widthFix"></image>
			<div v-if="isUpdataBox">
				<div v-if="!isUserSubmitted">
					<div class="upgradeTitle-One">当前{{updataName}}已是最新版本</div>
					<div class="upgradeTitle-Two">无需升级</div>
					<div class="confirmBox" @click="confirmUpBtn">
						<image src="@/static/confirm.png" style="width:200rpx;" mode="widthFix"></image>
					</div>
				</div>
				<div v-else>
					<div class="upgradeTitle-Three">已提交升级请求,请联系客服人员</div>
					<div class="confirmBox" @click="confirmUserBtn">
						<image src="@/static/confirm.png" style="width:200rpx;" mode="widthFix"></image>
					</div>
				</div>
			</div>
			<div v-else>
				<div v-if="!writeFinish">
					<div v-if="isUpdataFile">
						<div class="cloudUpdataImageBox">
							<image :src="imageName('/cloudUpdataImage.gif')" style="width:200rpx;" mode="widthFix"></image>
						</div>
						<div class="upgradeTitle-One">升级中</div>
						<div class="upgradeTitle-Two">请勿退出当前页面</div>
					</div>
					<div v-else>
						<div class="upgradeTitle-Three">更新失败,请联系客服人员</div>
						<div class="confirmBox" @click="confirmUserBtn">
							<image src="@/static/confirm.png" style="width:200rpx;" mode="widthFix"></image>
						</div>
					</div>
				</div>
				<div v-else>
					<div class="upgradeTitle-One">恭喜</div>
					<div class="upgradeTitle-Two">您已升级到{{updataName}}最新版本</div>
					<div class="confirmBox" @click="confirmUpBtn">
						<image src="@/static/confirm.png" style="width:200rpx;" mode="widthFix"></image>
					</div>
				</div>
			</div>
		</div>
		<div class="upgradeBox" v-if="isErrorBox">
			<image src="@/static/upgradeBox.png" style="width:100%;" mode="widthFix"></image>
			<div>
				<div class="upgradeTitle-One">{{updataName}}</div>
				<div class="upgradeTitle-Two">{{errorNameBox}}</div>
				<div class="confirmBox" @click="dischargeClick">
					<image src="@/static/confirm.png" style="width:200rpx;" mode="widthFix"></image>
				</div>
			</div>
		</div>
		<div class="upgradeBox" v-if="isShow">
			<image src="@/static/upgradeBox.png" style="width:100%;" mode="widthFix"></image>
			<div>
				<div class="upgradeTitle-One">放电状态不支持设备升级</div>
				<div class="upgradeTitle-Two">请断开车辆连接再重新尝试</div>
				<div class="confirmBox" @click="dischargeClick">
					<image src="@/static/confirm.png" style="width:200rpx;" mode="widthFix"></image>
				</div>
			</div>
		</div>
		<div v-if="isHardWare">
			<uni-popup ref="inputDialog" type="dialog">
				<uni-popup-dialog ref="inputClose" mode="input" title="输入内容" placeholder="请输入内容"
					@confirm="dialogInputConfirm()"></uni-popup-dialog>
			</uni-popup>
		</div>
		<div class="headImageBox" @click="inputDialogToggle()">
			<image :src="avaurl" style="width:83rpx;" mode="widthFix"></image>
		</div>
		<div class="cloudImageBox" @click="downLoadClick()">
			<image src="@/static/cloud.png" style="width:83rpx;" mode="widthFix"></image>
		</div>
		<div class="scrollViewBox" v-if="isShowFile">
			<div class="topViewBox">
				<div v-for="(item,index) in fileArray">
					<div class="fileLabelBox" @click="selectUpdataFile(item)">{{item.name}}</div>
				</div>
			</div>
			<div class="bottomViewBox">
				<div class="btn" @click="cancelUpdata()">取消更新</div>
			</div>
		</div>
	</div>
</template>

<script>
	import imageName from '@/utils/imageFormat.js';
	import {
		getUpgrade,
		getDoUpgrade
	} from "@/api/index.js"
	export default {
		data() {
			return {
				imageName,
				avaurl: "",
				//放电正常
				isSuccse: false,
				//放电异常
				isError: false,
				//下载
				isUpdata: false,
				isUpdataBox: false,
				//
				isHardWare: false,
				updataName: '',
				fileName: '',
				car: '',
				errorName: '',
				isEnd: false,
				thoroughfareOne: '',
				thoroughfareTwo: '',
				timerInterVal: '', //用来实时发送
				sendTimeout:'',
				sendTimeoutIndex:0,
				deviceId: '', //蓝牙设备id
				serviceId: '', //蓝牙服务id
				notifycharacteristicId: '', //蓝牙特证值
				characteristicId: '',
				dischargePower: 50, //放电功率
				bluetoothName: "aaa", //蓝牙
				arrayBuffer: [], //
				bufferName: undefined,
				pos: 0,
				bytes: 0,
				index: 0,
				writeBool: true,
				writeFinish: false,
				dataView: undefined,
				crcBuffer: undefined,
				isShow:false,
				isSingleChannel:false,
				isShowMessage:false,
				fileArray:[],
				isShowFile:false,
				isUserSubmitted:false,
				timer:undefined,
				isUpdataFile:true,
				isErrorBox:false,
				errorNameBox:"",
				statuslist: [{
						label: "主机状态",
						value: "已开机",
					},
					{
						label: "插枪状态",
						value: "未插枪",
					},
					{
						label: "内置电池",
						value: "99%",
					},
					{
						label: "输出电压",
						value: "0.0V",
					},
					{
						label: "输出电流",
						value: "0.00A",
					},
					{
						label: "车辆电压",
						value: "0.0V",
					},
					{
						label: "运行代码",
						value: "0000",
					},
					{
						label: "固件版本",
						value: "V1.1",
					},
					{
						label: "",
						value: "",
					},
				],
				btnlist: ["使用说明", "连接云端", "升级固件"],
			};
		},
		created() {},
		onLoad(option) {
			console.log("option",option);
			this.deviceId = option.deviceId;
			this.bluetoothName = option.name;
		},
		onShow() {
			this.getServices();
			this.isShowMessage = false;
		},
		onUnload(){
			clearInterval(this.timer);
			this.timer = undefined;
		   this.closeConnect();	
		},
		mounted() {
			this.avaurl = this.$store.state?.imageurl || '@/static/headImage.jpg';
		},
		methods: {
			cancelUpdata(){
				this.isShowFile = false;
			},
			confirmUserBtn(){
				this.isUpdata = false;
				this.isUpdataBox = false;
				this.isUserSubmitted = false;
				this.isUpdataFile = true;
			},
			confirmUpBtn() {
				this.isUpdata = false;
				this.isUpdataBox = false;
				this.writeFinish = false;
				let that = this;
				let buffer = that.searchCarState();
				this.timerInterVal = setInterval(() => {
					that.send(buffer);
				}, 500);
				clearInterval(this.sendTimeout);
				this.sendTimeoutIndex = 0;
			},
			dischargeClick(){
				this.isShow = false;
				this.isErrorBox = false;
			},
			downLoadClick() {
				if (this.isSuccse == true) {
					this.isShow = true;
					return
				}
				let that = this;
				clearInterval(this.timerInterVal);
				that.isUpdataBox = false;
				that.isShowFile = false;
				that.isUserSubmitted = false;
				that.fileArray = [];
				uni.showLoading({})
				//this.updataName.split('_')[0]
				getUpgrade({version:this.updataName.split('_')[0]}).then((res) => {
                        console.log("res",res);
						uni.hideLoading();
						if(res.data.length > 0)
						{
							this.fileArray = res.data;
							this.isShowFile = true;
						}
						else
						{
							if(res.msg == "当前版本为最新版本，无需升级")
							{
							   that.isUpdata = true;
							   that.isUpdataBox = true;
							}
							else if(res.msg == "已提交升级请求" || res.msg == "等待客服指定更新包")
							{
								that.isUpdata = true;
								that.isUpdataBox = true;
								that.isUserSubmitted = true;
							}
							else
							{
								uni.showToast({
									title:res.msg
								})
							}
						}
					}).catch((error) => {
						if (error.code === 401) {
							uni.navigateTo({
								url: `/pages/login/login`
							})
						}
						if(error.code === 400)
						{
							if(error.msg === "无更新包或版本为最新版本")
							{
								that.isUpdata = true;
								that.isUpdataBox = true;
							}
						}
					})
					.finally(() => {
						uni.hideLoading();
					})

			},
			selectUpdataFile(e){
				console.log(e.title,e.file_url);
				this.isShowFile = false;
				this.fileName = e.title;
				let that = this;
				uni.showLoading({
					title: '文件下载中'
				})
					uni.downloadFile({
						url: e.file_url,
						success(res) {
							
							uni.hideLoading();
							that.isUpdata = true;
							that.fileSelect(res);
						},
						fail: (err) => {
							uni.showToast({
								title: '文件下载错误'
							})
						}
					});
			},
			dialogInputConfirm(val) {			
				if (val == "debug2268") {
					clearInterval(this.timerInterVal);
					uni.navigateTo({
						url: `/pages/hardware/hardware?deviceId=${this.deviceId}`
					})
				}
				if(val == "888888")
				{
					this.isErrorBox = true;
				}
			},
			inputDialogToggle() {
				this.isHardWare = true;
				this.$refs.inputDialog.open()
			},
			switch2Change(e) {
				console.log(e.detail.value);
			},
			//测试
			fileSelect(e) {
				this.toArrayBuffer(e.tempFilePath);
				console.log("升级发送数据");
				let arrayBufferFileName = this.str_to_hex(this.fileName);
				let arrayBufferFileSize = this.str_to_hex(e.dataLength.toString())
				let len = 128;
				let buffer = new ArrayBuffer(len);
				let dataView = new DataView(buffer);
				for (let i = 0; i < arrayBufferFileName.length; i++) {
					dataView.setUint8(i, "0x" + arrayBufferFileName[i]);
				}
				dataView.setUint8(arrayBufferFileName.length, 0x00);
				for (let i = 0; i < arrayBufferFileSize.length; i++) {
					dataView.setUint8(arrayBufferFileName.length + 1 + i, "0x" + arrayBufferFileSize[i]);
				}
				this.crcBuffer = this.crc16modbus(buffer);
				let newbuffer = new ArrayBuffer(130);
				let newDataView = new DataView(newbuffer);
				for (let i = 0; i < newbuffer.byteLength; i++) {
					if (i == 128) {
						newDataView.setUint8(i, this.crcBuffer[1]);
					} else if (i == 129) {
						newDataView.setUint8(i, this.crcBuffer[0]);
					} else {
						console.log(dataView.getUint8(i));
						newDataView.setUint8(i, dataView.getUint8(i));
					}
				}
				this.bytes = newbuffer.byteLength;
				this.bufferName = newbuffer;
				this.updateHardware();
			},
			toArrayBuffer(chunk) {
				uni.getFileSystemManager().readFile({
					filePath: chunk,
					encoding: 'base64',
					success: (res) => {
						console.log(uni.base64ToArrayBuffer(res.data));
						var array = uni.base64ToArrayBuffer(res.data);
						if (array instanceof ArrayBuffer) {
							array = new Uint8Array(array);
						}
						let index = Math.ceil(array.byteLength / 1024);
						let len = array.byteLength;
						let pos = 0;
						for (let i = 0; i < index; i++) {
							if (len > 1024) {
								let buffer = array.slice(pos, pos + 1024);
								// let data = new DataView(buffer);
								let crc = this.crc16modbus(buffer);
								let newBuffer = new ArrayBuffer(buffer.byteLength + 2);
								let dataView = new DataView(newBuffer);
								for (let i = 0; i < newBuffer.byteLength; i++) {
									if (i == 1024) {
										dataView.setUint8(i, crc[1]);
									} else if (i == 1025) {
										dataView.setUint8(i, crc[0]);
									} else {
										dataView.setUint8(i, buffer[i]);
									}

								}
								pos += 1024;
								len -= 1024;
								this.arrayBuffer.push(newBuffer);
							} else {
								let buffer = array.slice(pos, pos + len);
								let oldBuffer = new ArrayBuffer(1024);
								let oldDataView = new DataView(oldBuffer);
								for (let i = 0; i < oldBuffer.byteLength; i++) {
									if (i < buffer.byteLength) {
										oldDataView.setUint8(i, buffer[i]);
									} else {
										oldDataView.setUint8(i, 0x1A);
									}
								}
								let crc = this.crc16modbus(oldBuffer);
								let newBuffer = new ArrayBuffer(1026);
								let dataView = new DataView(newBuffer);
								for (let i = 0; i < newBuffer.byteLength; i++) {
									if (i == 1024) {
										dataView.setUint8(i, crc[1]);
									} else if (i == 1025) {
										dataView.setUint8(i, crc[0]);
									} else {
										dataView.setUint8(i, oldDataView.getUint8(i));
									}

								}
								this.arrayBuffer.push(newBuffer);
							}


						}


					}
				})
			},
			//返回新字节数组
			backArrayBuffer(length) {
				var buffer = new ArrayBuffer(length);
				let dataView = new DataView(buffer);
				for (let i = 0; i < length; i++) {
					dataView.setUint8(i, 0x00);
				}
				return buffer;
			},
			//循环请求发送数据
			forArrayBuffer(buffer, crcBuffer, index, length, posIndexs) {
				console.log("发送数据", buffer, crcBuffer, index, length, posIndexs);
				let pos = index;
				let posIndex = posIndexs;
				let bytes = length;
				let len = bytes - posIndex > 20 ? 20 : bytes - posIndex;

				var bufferNew = new ArrayBuffer(len);
				let dataView = new DataView(bufferNew);
				if (bytes - posIndex > 20) {
					if (posIndex == 0) {
						dataView.setUint8(0, 0x01);
						dataView.setUint8(1, 0x00);
						dataView.setUint8(2, 0xFF);
						for (let i = 0; i < len - 3; i++) {
							dataView.setUint8(i + 3, buffer.getUint8(i));
						}
					} else {
						for (let i = 0; i < len; i++) {
							dataView.setUint8(i, buffer.getUint8(pos + i));
						}
					}
					pos = pos == 0 ? pos + 17 : pos + 20;
					posIndex = posIndex + 20;
				} else {
					console.log("最后一次", pos, len, bytes);
					for (let i = 0; i < len; i++) {

						if (i == 11) {

							dataView.setUint8(i, crcBuffer[1]);
						} else if (i == 12) {
							dataView.setUint8(i, crcBuffer[0]);
						} else {
							dataView.setUint8(i, buffer.getUint8(pos + i));
						}


					}

					pos = 0;
					posIndex = 0;
				}
				let that = this;
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					value: bufferNew,
					success(res) {
						console.log(res, pos);
						if (pos > 0) {
							that.forArrayBuffer(that.dataView, that.crcBuffer, pos, bytes, posIndex);
						}

					},
					fail(res) {
						console.error('error,write', res);
						if (res.errCode === 10006) {
							clearInterval(that.timerInterVal);
							if(that.isShowMessage == false)
							{
								that.isShowMessage = true;
								uni.showLoading({
									title: '你已经断开蓝牙连接,3秒后返回上个页面',
								})
								setTimeout(() => {
									uni.hideLoading();
									uni.navigateBack({
										delta: 1,
									})
								}, 3000)
							}
						}
					}
				})

			},
			//获取服务UUid
			getServices() {
				let that = this;
				uni.getBLEDeviceServices({
					deviceId: that.deviceId,
					success(res) {
						console.log("第一次",res);
						for(let i=0;i<res.services.length;i++)
						{
							 if(res.services[i].uuid == "0000FFF0-0000-1000-8000-00805F9B34FB")
							 {
								 that.serviceId = res.services[i].uuid || "";
							 }
						}
						that.getCharacteristics();
					},
					fail(err) {
						console.error("error", err)
					}
				})
			},
			//获取蓝牙特征值
			getCharacteristics() {
				let that = this;
				console.log(that.serviceId,that.deviceId, '获取特性值/UUID');
				uni.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					success(res) {
						console.log("res",res);
						for(let i=0;i<res.characteristics.length;i++)
						{
							 if(res.characteristics[i].uuid == "0000FFF2-0000-1000-8000-00805F9B34FB")
							 {
								 that.characteristicId = res.characteristics[i].uuid || "";
							 }
							 if(res.characteristics[i].uuid == "0000FFF1-0000-1000-8000-00805F9B34FB")
							 {
							 	 that.notifycharacteristicId = res.characteristics[i].uuid || "";		
							 }
						}
						
						that.notify();
					},
					fail(err) {
						console.error("特性值",err)
					}
				})
			},
			//开启蓝牙信息监听
			notify() {
				let that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true,
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.notifycharacteristicId,
					success(res) {
						let buffer = that.searchCarState();
						that.timerInterVal = setInterval(() => {
							that.send(buffer);
						}, 500);

						uni.onBLECharacteristicValueChange(function(characteristic) {
							let x = new Uint8Array(characteristic.value);
							if (x.byteLength > 60) {
								that.updataName = that.arrayBufferUTF8ToStr(characteristic.value)
							} else {
								let strHex = ""
								let str = ""
								for (let i = 0; i < x.length; i++) {
									strHex = strHex + x[i].toString(16).padStart(2, "0")
									str = str + String.fromCharCode(x[i])
								};
								if (strHex == 43 && that.writeBool == true) {
									console.log("发送成功1")
									that.writeBool = false;
									// that.forArrayBuffer(that.dataView,that.crcBuffer,0,133);
									that.writeTest(that.bufferName, 1, "name");
									that.sendTimeout = setInterval(() => {
										that.sendTimeoutIndex++
										if(that.sendTimeoutIndex > 3)
										{
											clearInterval(that.sendTimeout);
											if(that.isShowMessage == false)
											{
												that.isShowMessage = true;
												uni.showLoading({
													title: '你已经断开蓝牙连接,3秒后返回上个页面',
												})
												setTimeout(() => {
													uni.hideLoading();
													uni.navigateBack({
														delta: 1,
													})
												}, 3000)
											}
										}
									}, 1000);
								} else if (strHex.toString() == "0643" || strHex.toString() == "06") {
								
									if (that.index < that.arrayBuffer.length) {
										console.log("正在更新,发送成功")
										that.bufferName = that.arrayBuffer[that.index];
										that.pos = 0;
										that.bytes = that.bufferName.byteLength;
										that.index++;
										that.writeTest(that.bufferName, 1, "file");
									} else {
										if (strHex.toString() == "06") {
											if (that.writeFinish == false) {
												getDoUpgrade({version:that.updataName.split('_')[0],success:1}).then((res)=>{
													console.log("升级成功",res);
												})
												clearInterval(that.timer)
												//升级成功
												that.writeFinish = true;
												let buffer = new ArrayBuffer(1);
												let dataView = new DataView(buffer);
												dataView.setUint8(0, 0x04);
												that.send(buffer);
											}


										} else {
											let buffer = new ArrayBuffer(128);
											let dataView = new DataView(buffer);
											for (let i = 0; i < 128; i++) {
												dataView.setUint8(i, 0x00);
											}
											that.crcBuffer = that.crc16modbus(buffer);
											let newBuffer = new ArrayBuffer(133);
											let newDataView = new DataView(newBuffer);
											newDataView.setUint8(0, 0x01);
											newDataView.setUint8(1, 0x00);
											newDataView.setUint8(2, 0xFF);
											for (let i = 3; i < 131; i++) {
												newDataView.setUint8(i, dataView.getUint8(i - 3));
											}
											newDataView.setUint8(131, that.crcBuffer[1]);
											newDataView.setUint8(132, that.crcBuffer[0]);
											that.bufferName = newBuffer;
											that.pos = 0;
											that.bytes = that.bufferName.byteLength;
											that.writeTest(that.bufferName, 0, "");
										}

									}
								} else if (strHex.toString() == "15") {
									let buffer = new ArrayBuffer(1);
									let dataView = new DataView(buffer);
									dataView.setUint8(0, 0x04);
									that.send(buffer);
								}
								// console.log(str, strHex.toString())
							}

							// console.log('characteristic value comed:', characteristic);
							// console.log('ab2hex=========', that.ab2hex(characteristic.value));
							// console.log('arrayBufferUTF8ToStr=========', that.arrayBufferUTF8ToStr(
							// 	characteristic.value));
							// console.log('hex2int=========', that.hex2int(characteristic.value));

						});
					},
					fail(res) {
						console.error("通知",res);
					}
				})
			},

			//发送数据
			send(buffer) {
				let that = this;
				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.characteristicId,
					value: buffer,
					success(res) {

					},
					fail(res) {
						if (res.errCode === 10006) {
							clearInterval(that.timerInterVal);
							if(that.isShowMessage == false)
							{
								that.isShowMessage = true;
								uni.showLoading({
									title: '你已经断开蓝牙连接,3秒后返回上个页面',
								})
								setTimeout(() => {
									uni.hideLoading();
									uni.navigateBack({
										delta: 1,
									})
								}, 3000)
							}
							
						}
					}
				})
			},
			// 十进制转十六进制
			jinzhi_change(num, system) {
				// 十进制转其它进制，仅支持到十六进制
				var shiliu = [
						'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G'
					],
					sl_arr = [];
				do {
					var fl_sl = Math.floor(num / system);
					var yu_sl = num % system;

					sl_arr.unshift(shiliu[yu_sl]); //往数组开头添加一条数据
					num = fl_sl;
				} while (num > 0)
				return sl_arr.join(''); //拼接数组成字符串
			},
			//字符串转16进制码
			str_to_hex(str) {
				var val = "";
				for (var i = 0; i < str.length; i++) {
					if (val == "")
						val = str.charCodeAt(i).toString(16);
					else
						val += "," + str.charCodeAt(i).toString(16);
				}
				return val.split(",");
			},
			// ArrayBuffer转16进度字符串示例 
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},

			hex2int(hex) { //16进制转10进制
				var len = hex.length,
					a = new Array(len),
					code;
				console.log(len);
				for (var i = 0; i < len; i++) {

					code = hex.charCodeAt(i);
					if (48 <= code && code < 58) {
						code -= 48;
					} else {
						code = (code & 0xdf) - 65 + 10;
					}
					a[i] = code;
				}

				return a.reduce(function(acc, c) {
					acc = 16 * acc + c;
					return acc;
				}, 0);

			},
			searchCarState() {
				var buffer = new ArrayBuffer(15);
				let dataView = new DataView(buffer);
				for (let i = 0; i < 15; i++) {
					dataView.setUint8(i, 0x00);
				}
				this.crcBuffer = this.crc16modbus(buffer);
				var newbuffer = new ArrayBuffer(19)
				let newDataView = new DataView(newbuffer);
				newDataView.setUint8(0, 0xA5);
				for (var i = 0; i < 15; i++) {
					newDataView.setUint8(i + 1, dataView.getUint8(i));

				}
				newDataView.setUint8(16, this.crcBuffer[1]);
				newDataView.setUint8(17, this.crcBuffer[0]);
				newDataView.setUint8(18, 0x5A);
				return newbuffer;
			},
			arrayBufferUTF8ToStr(array) {
				let that = this;
				var out, i, len, c;
				var char2, char3;
				if (array instanceof ArrayBuffer) {
					array = new Uint8Array(array);
				}
				console.log("进来了", array.length);
				len = array.length;
				if (array[27] == 0) {
					this.isSuccse = false;
					this.isError = false;
				} else if (array[27] == 2) {
					this.isSuccse = true;
					this.isError = false;
					this.car = array[28];
					this.thoroughfareOne = ((array[32] * 256 + array[33]) / 1000).toFixed(2);
					this.thoroughfareTwo = ((array[34] * 256 + array[35]) / 1000).toFixed(2);
				} else if (array[27] == 3) {
					this.isSuccse = false;
					this.isError = true;
					if(array[36] == 4 || array[36] == 5 || array[36] == 19)
					{
						this.errorName = "过温保护" + "(" + array[36]+")"
					}
					else if(array[36] == 0)
					{
						this.errorName = "无错误码(0)"
					}
					else
					{
						this.errorName = "放电异常" + "(" + array[36]+")"
					}
					
				}
				if(array[36] == 4 || array[36] == 5 || array[36] == 19)
				{
					this.errorNameBox = "过温保护" + "(" + array[36]+")"
				}
				else if(array[36] == 0)
				{
					this.errorNameBox = "无错误码(0)"
				}
				else
				{
					this.errorNameBox = "放电异常" + "(" + array[36]+")"
				}
				if (this.isEnd === true) {
					this.isEnd = false;
					let buffer = that.searchCarState();
					this.timerInterVal = setInterval(() => {
						that.send(buffer);
					}, 500);
				}
				console.log("thoroughfareTwo",this.thoroughfareTwo);
				if(this.thoroughfareTwo >= 65.53)
				{
					this.isSingleChannel = true;
				}
				else
				{
					this.isSingleChannel = false;
				}
				let strHex = "";
				let str = "";
				for (let i = 1; i < 27; i++) {
					strHex = strHex + array[i].toString(16).padStart(2, "0")
					str = str + String.fromCharCode(array[i])
				};

				return str;
			},
			crc16modbus(str) {
				let crc = 0x0000; // 效验初始值
				const buffer = Buffer.from(str)
				for (const byte of buffer) {
					for (let j = 0; j < 8; j++) {
						const bit = ((byte >> (7 - j) & 1) == 1);
						const c15 = ((crc >> 15 & 1) == 1);
						crc <<= 1;
						if (c15 ^ bit)
							crc ^= 0x1021;
					}
				}
				crc &= 0xffff;
				var crcLow = crc & 0xFF;
				var crcHigh = (crc >> 8) & 0xFF;
				return [crcLow, crcHigh];
			},
			writeTest(buffer, type, title) {
				let that = this;
				let tmpBuffer;
				if (type == 1) {
					if (title == 'name') {
						tmpBuffer = new ArrayBuffer(3);
						let dataView = new DataView(tmpBuffer);
						dataView.setUint8(0, 0x01);
						dataView.setUint8(1, 0x00);
						dataView.setUint8(2, 0xFF);
						uni.writeBLECharacteristicValue({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.characteristicId,
							value: tmpBuffer,
							success: () => {
								that.sendTimeoutIndex = 0;
								that.writeTest(that.bufferName, 0, "");
							},
							fail: (res) => {
								if (res.errCode === 10006) {
									clearInterval(that.timerInterVal);
									if(that.isShowMessage == false)
									{
										 that.isShowMessage = true;
										 uni.showLoading({
										 	title: '你已经断开蓝牙连接,3秒后返回上个页面',
										 })
										 setTimeout(() => {
										 	uni.hideLoading();
										 	uni.navigateBack({
										 		delta: 1,
										 	})
										 }, 3000)
									}
									
								}
							}
						})
					}
					if (title == "file") {
						tmpBuffer = new ArrayBuffer(3);
						let dataView = new DataView(tmpBuffer);
						dataView.setUint8(0, 0x02);
						if (this.index < 10) {
							dataView.setUint8(1, "0x0" + this.index);
							dataView.setUint8(2, ~("0x0" + this.index));
						} else {
							dataView.setUint8(1, this.index);
							dataView.setUint8(2, ~this.index);
						}

						uni.writeBLECharacteristicValue({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.characteristicId,
							value: tmpBuffer,
							success: () => {
								console.log("发送成功2")
								that.sendTimeoutIndex = 0;
								that.writeTest(that.bufferName, 0, "");
							},
							fail: (res) => {
								console.log("发送失败");
								if (res.errCode === 10006) {
									clearInterval(that.timerInterVal);
									if(that.isShowMessage == false)
									{
										 that.isShowMessage = true;
										 uni.showLoading({
										 	title: '你已经断开蓝牙连接,3秒后返回上个页面',
										 })
										 setTimeout(() => {
										 	uni.hideLoading();
										 	uni.navigateBack({
										 		delta: 1,
										 	})
										 }, 3000)
									}
									
								}
							}
						})
					}
				} else {
					if (this.bytes > 20) {
						tmpBuffer = buffer.slice(this.pos, this.pos + 20);
						this.pos += 20;
						this.bytes -= 20;
						uni.writeBLECharacteristicValue({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.characteristicId,
							value: tmpBuffer,
							success: () => {
								console.log("发送成功3")
								that.sendTimeoutIndex = 0;
								that.writeTest(that.bufferName, 0, "");
							},
							fail: (res) => {
								console.log("发送失败123",res);
								if (res.errCode === 10006) {
									clearInterval(that.timerInterVal);
									if(that.isShowMessage == false)
									{
										that.isShowMessage = true;
										uni.showLoading({
											title: '你已经断开蓝牙连接,3秒后返回上个页面',
										})
										setTimeout(() => {
											uni.hideLoading();
											uni.navigateBack({
												delta: 1,
											})
										}, 3000)
									}
									
								}
							}
						})
					} else {
						tmpBuffer = buffer.slice(this.pos, this.pos + this.bytes);
						this.pos += this.bytes;
						this.bytes -= this.bytes;
						uni.writeBLECharacteristicValue({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.characteristicId,
							value: tmpBuffer,
							success: () => {
								
								console.log("发送成功")
								that.sendTimeoutIndex = 0;
							},
							fail: (res) => {
								console.log("发送失败");
								if (res.errCode === 10006) {
									clearInterval(that.timerInterVal);
									if(that.isShowMessage == false)
									{
										that.isShowMessage = true;
										uni.showLoading({
											title: '你已经断开蓝牙连接,3秒后返回上个页面',
										})
										setTimeout(() => {
											uni.hideLoading();
											uni.navigateBack({
												delta: 1,
											})
										}, 3000)
									}
								
								}
							}
						})
					}
				}
				
				if(that.writeFinish == false)
				{
					clearInterval(that.timer)
					that.timer = undefined;
					that.timer = setInterval(()=>{
						getDoUpgrade({version:that.updataName.split('_')[0],success:1}).then((res)=>{
							console.log("升级失败",res);
						})
						that.isUpdataFile = false;
						clearInterval(that.timer)
						that.timer = undefined;
					},2000)
				}
			},
			updateHardware() {
				let arrayBufferFileName = this.str_to_hex("ver:"+this.fileName);

				console.log("hex", arrayBufferFileName);
				var buffer = new ArrayBuffer(arrayBufferFileName.length);
				let dataView = new DataView(buffer);
				for (let i = 0; i < arrayBufferFileName.length; i++) {
					console.log("0x" + arrayBufferFileName[i]);
					dataView.setUint8(i, "0x" + arrayBufferFileName[i]);
				}
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					value: buffer,
					success(res) {

					},
					fail(res) {
						console.error('error,write', res.errCode);
						if (res.errCode === 10006) {
							clearInterval(that.timerInterVal);
							if(this.isShowMessage == false)
							{
								this.isShowMessage = true;
								uni.showLoading({
									title: '你已经断开蓝牙连接,3秒后返回上个页面',
								})
								setTimeout(() => {
									uni.hideLoading();
									uni.navigateBack({
										delta: 1,
									})
								}, 3000)
							}
						}
					}
				})
				clearInterval(this.timer)
				this.timer = undefined;
				this.timer = setInterval(()=>{
					getDoUpgrade({version:this.updataName.split('_')[0],success:1}).then((res)=>{
						console.log("升级失败",res);
					})
					this.isUpdataFile = false;
					clearInterval(this.timer)
					this.timer = undefined;
				},2000)
			},
			closeCar() {
				if (this.isSuccse == false) {
					return
				}
				// if(this.isUpdata == true)
				// {
				// 	return
				// }
				let that = this;
				clearInterval(that.timerInterVal);
				var buffer = new ArrayBuffer(15);
				let dataView = new DataView(buffer);
				for (let i = 0; i < 15; i++) {
					if (i == 0) {
						dataView.setUint8(i, 0x01);
					} else if (i == 2) {
						dataView.setUint8(i, 0x01);
					} else {
						dataView.setUint8(i, 0x00);
					}
				}
				that.crcBuffer = that.crc16modbus(buffer);
				var newbuffer = new ArrayBuffer(19)
				let newDataView = new DataView(newbuffer);
				newDataView.setUint8(0, 0xA5);
				for (var i = 0; i < 15; i++) {
					newDataView.setUint8(i + 1, dataView.getUint8(i));

				}
				newDataView.setUint8(16, that.crcBuffer[1]);
				newDataView.setUint8(17, that.crcBuffer[0]);
				newDataView.setUint8(18, 0x5A);
				that.isEnd = true;
				that.send(newbuffer);
			},
			closeConnect(){
				console.log("进来1")
				if(this.deviceId)
				{
					console.log("进来2")
					uni.closeBLEConnection({
						deviceId:this.deviceId,
						success:(res)=>{
						},
						fail:(error)=>{
							
						}
					})
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	.detail {
		width: 100%;
		height: 100%;
		overflow-y: hidden;
		position: relative;
		background-image: url("https://edu.hailun-music.com/static/weidian/bgImage.png");
		background-size: 100%;
		background-color: rgba(205,224,243, 1);
		.imageBox {
			width: 100%;
			height: 100%;
		}

		.headImageBox {
			width: 53rpx;
			height: 53rpx;
			background: #92BEF2;
			border: 1px solid #92BEF2;
			border-radius: 50%;
			position: absolute;
			top: 80rpx;
			left: 30rpx;
			overflow: hidden;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.cloudImageBox {
			width: 53rpx;
			height: 53rpx;
			background: #92BEF2;
			border: 1px solid #92BEF2;
			border-radius: 50%;
			position: absolute;
			top: 80rpx;
			left: 100rpx;
			z-index: 80;
			overflow: hidden;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.scrollViewBox{
			width:70%;
			background-color: white;
			position: absolute;
			border-radius:20rpx;
			top:600rpx;
			left:15%;
			z-index:200;
			.topViewBox{
				width: 100%;
				height: 312rpx;
				margin-top: 20rpx;
				padding:0 20rpx;
				box-sizing: border-box;
				overflow-y: hide;
				.fileLabelBox{
					width: 100%;
					padding:20rpx 0;
					box-sizing: border-box;
					border-bottom:1rpx solid #eee;
					font-size: 26rpx;
					font-family: PingFangSC, 'Microsoft YaHei';
					text-align: center;
				}
			}
			.bottomViewBox{
				width:100%;
				height: 88rpx;
				text-align: center;
				.btn{
				   height:100%;
				   padding:0 30rpx;
				   box-sizing: border-box;
				   line-height: 88rpx;
				}
			}
		}
		.upgradeBox {
			width: 100%;
			position: absolute;
			top: 693.59rpx;
			left: 0;
			overflow: hidden;
			padding: 0 5%;
			box-sizing: border-box;
			display: flex;
			justify-content: center;
			
			.upgradeTitle-One {
				width: 100%;
				text-align: center;
				position: absolute;
				top: 58rpx;
				left: 0;
				color: rgba(37, 39, 46, 1);
				font-size: 26rpx;
				font-weight: 400;
				line-height: 1;
				font-family: PingFangSC, 'Microsoft YaHei';
			}
			
			.upgradeTitle-Two {
				width: 100%;
				text-align: center;
				position: absolute;
				top: 110rpx;
				left: 0;
				color: rgba(37, 39, 46, 1);
				font-size: 26rpx;
				font-weight: 400;
				line-height: 1;
				font-family: PingFangSC, 'Microsoft YaHei';
			}
			.upgradeTitle-Three{
				width: 100%;
				text-align: center;
				position: absolute;
				top: 80rpx;
				left: 0;
				color: rgba(37, 39, 46, 1);
				font-size: 26rpx;
				font-weight: 400;
				line-height: 1;
				font-family: PingFangSC, 'Microsoft YaHei';
			}
			.confirmBox {
				width: 200rpx;
				position: absolute;
				top: 160rpx;
				left: 36%;
			}

			.cloudUpdataImageBox {
				width: 200rpx;
				position: absolute;
				top: 110rpx;
				left: 36%;
			}
		}

		.bottomImageBox {
			width: 100%;
			position: relative;
			position: absolute;
			top: 0;
			left: 0;

			.title-line-one {
				width: 50%;
				z-index: 2;
				text-align: center;
				font-size: 62rpx;
				color: rgba(140, 186, 241, 1);
				position: absolute;
				font-weight: 400;
				top: 1127.56rpx;
				left: 0;
				letter-spacing: 10rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
			}
            .title-line-singleOne{
				width: 100%;
				z-index: 2;
				text-align: center;
				font-size: 62rpx;
				color: rgba(140, 186, 241, 1);
				position: absolute;
				font-weight: 400;
				top: 1127.56rpx;
				left: 0;
				letter-spacing: 10rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
			}
			.title-line-singleTwo{
				width: 100%;
				z-index: 2;
				text-align: center;
				font-size: 25.64rpx;
				color: rgba(140, 186, 241, 1);
				position: absolute;
				font-weight: 400;
				top: 1208.33rpx;
				left: 0;
				letter-spacing: 2rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
			}
			.title-line-two {
				width: 50%;
				z-index: 2;
				text-align: center;
				font-size: 25.64rpx;
				color: rgba(140, 186, 241, 1);
				position: absolute;
				font-weight: 400;
				top: 1208.33rpx;
				left: 0;
				letter-spacing: 2rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
			}

			.title-line-three {
				width: 50%;
				z-index: 2;
				text-align: center;
				font-size: 62rpx;
				color: rgba(140, 186, 241, 1);
				position: absolute;
				font-weight: 400;
				top: 1127.56rpx;
				left: 50vw;
				letter-spacing: 10rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
			}

			.title-line-four {
				width: 50%;
				z-index: 2;
				text-align: center;
				font-size: 25.64rpx;
				color: rgba(140, 186, 241, 1);
				position: absolute;
				font-weight: 400;
				top: 1208.33rpx;
				left: 50vw;
				letter-spacing: 2rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
			}

			.title-error-started {
				width: 100%;
				z-index: 2;
				text-align: center;
				font-size: 25.64rpx;
				color: rgba(251, 100, 100, 1);
				position: absolute;
				font-weight: 600;
				letter-spacing: 8rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
				top: 642.31rpx;
				left: 0;
			}

			.title-not-started {
				width: 100%;
				z-index: 2;
				text-align: center;
				font-size: 26rpx;
				color: rgba(123, 160, 191, 1);
				position: absolute;
				top: 642rpx;
				left: 0;
				font-weight: 600;
				letter-spacing: 6rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
			}

			.title-succes-one {
				width: 100%;
				z-index: 3;
				text-align: center;
				font-size: 25rpx;
				line-height: 1;
				color: rgba(37, 39, 46, 1);
				position: absolute;
				top: 517rpx;
				font-weight: 600;
				left: 0;
				letter-spacing: 8rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
			}

			.title-succes-two {
				width: 100%;
				z-index: 3;
				text-align: center;
				font-size: 90rpx;
				line-height: 1;
				position: absolute;
				color: rgba(37, 39, 46, 1);
				top: 566rpx;
				left: 0;
				font-weight: 600;
				font-family: PingFangSC, 'Microsoft YaHei';
			}

			.title-succes-three {
				width: 100%;
				z-index: 3;
				text-align: center;
				font-size: 25rpx;
				line-height: 1;
				position: absolute;
				color: rgba(37, 39, 46, 1);
				top: 658rpx;
				font-weight: 600;
				left: 0;
				letter-spacing: 8rpx;
				font-family: PingFangSC, 'Microsoft YaHei';
			}

			.titlebox {
				width: 120rpx;
				height: 120rpx;
				position: absolute;
				top: 1511.54rpx;
				left: 42%;
				z-index: 100;
				font-size: 25.64rpx;
				letter-spacing: 2rpx;
				color: rgba(94, 160, 238, 1);
				font-family: PingFangSC, 'Microsoft YaHei';
				text-align: center;
			}

			.title-not-Box {
				opacity: 0.3;
				width: 120rpx;
				height: 120rpx;
				position: absolute;
				top: 1511.54rpx;
				left: 42%;
				z-index: 100;
				font-size: 25.64rpx;
				letter-spacing: 2rpx;
				color: rgba(94, 160, 238, 1);
				font-family: PingFangSC, 'Microsoft YaHei';
				text-align: center;
			}

			.title-one {
				width: 100%;
				text-align: center;
				position: absolute;
				top: 1120rpx;
				left: 0;
				z-index: 1;
				font-size: 26rpx;
				color: rgba(143, 174, 201, 1);
				font-family: PingFangSC, 'Microsoft YaHei';
				letter-spacing: 8rpx;
				font-weight: 300;
				line-height: 1;
			}

			.title-two {
				width: 100%;
				text-align: center;
				position: absolute;
				top: 1160rpx;
				left: 0;
				z-index: 1;
				font-size: 26rpx;
				color: rgba(143, 174, 201, 1);
				font-family: PingFangSC, 'Microsoft YaHei';
				letter-spacing: 8rpx;
				font-weight: 300;
				line-height: 1;
			}

			.title-three {
				width: 100%;
				text-align: center;
				position: absolute;
				top: 1200rpx;
				left: 0;
				z-index: 1;
				font-size: 26rpx;
				color: rgba(143, 174, 201, 1);
				font-family: PingFangSC, 'Microsoft YaHei';
				letter-spacing: 8rpx;
				font-weight: 300;
				line-height: 1;
			}

			.title-four {
				width: 100%;
				text-align: center;
				position: absolute;
				top: 1240rpx;
				left: 0;
				z-index: 1;
				font-size: 26rpx;
				color: rgba(143, 174, 201, 1);
				font-family: PingFangSC, 'Microsoft YaHei';
				letter-spacing: 8rpx;
				font-weight: 300;
				line-height: 1;
			}

			.title-five {
				width: 100%;
				text-align: center;
				position: absolute;
				top: 1280rpx;
				left: 0;
				z-index: 1;
				font-size: 26rpx;
				color: rgba(143, 174, 201, 1);
				font-family: PingFangSC, 'Microsoft YaHei';
				letter-spacing: 8rpx;
				font-weight: 300;
				line-height: 1;
			}
		}

		.topImageBox {
			width: 100%;
			position: absolute;
			top: 0;
			left: 0;
		}


	}

	@keyframes fadeIn {
		0% {
			opacity: 1;
		}

		50% {
			opacity: 0.5;
		}

		100% {
			opacity: 1;
		}
	}

	.succes-image-Box {
		opacity: 1;
		animation: fadeIn 3s infinite;
		
	}

	image {
		display: block;
		font-size: 0;
	}
</style>